import 'dart:convert';

import 'package:base_flutter/base_flutter.dart';
// import 'package:car_lrp_plugin/car_lrp_plugin.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'package:visitor_scan_package/net/account/axun_user.dart';
import 'package:visitor_scan_package/net/api.dart';
import 'package:visitor_scan_package/net/response/scan_result_data.dart';
import 'package:visitor_scan_package/ui/scan_qr_page.dart';
import 'package:visitor_scan_package/ui/scan_result_page.dart';
import 'package:visitor_scan_package/utils/permission_center_config.dart';
import 'package:visitor_scan_package/utils/weiyang_scanner.dart';
import 'package:visitor_scan_package/widget/plate_no_keyboard.dart';

import '../net/response/baidu_plate_response.dart';
import '../net/response/token_response.dart';
import '../ui/login_page.dart';
import '../utils/permission_utils.dart';

class HomeScanViewModel extends BaseViewModel {
  HomeScanViewModel(BuildContext context) : super(context);

  String plateNo = "";

  var token = "";
  var expiresDate = "";
  final _format = [yyyy,'-',mm,'-',dd,' ',HH,':',nn,':',ss];

  Future<void> scanCode() async {
    Barcode? code = await Go().push(ScanQrPage());
    if (code != null) {
      var scanCodeStr = code.code!;
      submitCode(scanCodeStr);
    }
    // WeiyangScanner().openScanner((str){
    //   submitCode(str);
    // });
  }

  Future<void> plateNoScan() async {
    // if(token.isNullOrEmpty()){
    //   await getToken();
    // }else{
    //   var time = DateTime.parse(expiresDate);
    //   if(time.isBefore(DateTime.now())){
    //     await getToken();
    //   }
    // }
    // var code = await CarLrpPlugin.openScan(needApply: false);
    // if (code != null) {
    //   plateNo = code.code;
    //   notifyListeners();
    //   // var data = base64Encode(code.frame!);
    //   // getBaudiCarData(data);
    // }
  }

  Future<void> getBaudiCarData(String base64) async {
    showLoadingDialog();
    try{
      var data =  await PostRequest.getBaiduCar(token, base64);
      hideDialog();
      var bean = BaiduPlateResponse.fromJson(data);
      if(bean.wordsResult!=null){
        plateNo = bean.wordsResult!.number!;
        notifyListeners();
      }
    }catch(e){
      showToast(e.toNetError());
      hideDialog();
    }
  }

  void inputPlateNo() {
    PlateNoKeyboard(
        context: context,
        plateNo: plateNo,
        onClose: (code) {
          plateNo = code;
          notifyListeners();
        }).show();
  }

  Future<void> submitCode(String code) async {
    showLoadingDialog(msg: "提交中...");
    try {
      var result = await PostRequest.updateScan(code, plateNo);
      hideDialog();
      if (result['code'].toString() == '0') {
        var data = ScanResultData.fromJson(result['data']);
        Go().push(ScanResultPage(data));
      } else {
        showToast(result['msg']);
      }
      plateNo = "";
      notifyListeners();
    } catch (e) {
      hideDialog();
      showToast(e.toNetError());
      plateNo = "";
      notifyListeners();
    }
  }

  Future<void> checkLogin() async {
    try {
      await PostRequest.checkLogin();
    } catch (e) {
      var mst = e.toNetError();
      if (mst.contains('401')) {
        AxunUser.clearUser();
        Go().pushRemoveUntil(LoginPage(
          loginMsg: '登录失效，请重新登录',
        ));
      }
    }
  }

  Future<void> requestCamera() async {
    var permissions = [Permission.camera];
    if (await PermissionUtils.isLackPermissions(permissions)) {
      await PermissionUtils.requestPermissions(permissions);
    }
  }

  Future<void> getToken() async {
    showLoadingDialog();
    try{
      var data = await PostRequest.getBaiduToken();
      hideDialog();
      var bean  = TokenResponse.fromJson(data);
      if("0"==bean.code){
        token = bean.data!.accessToken!;
        expiresDate =  bean.data!.expiresDate!;
      }
    }catch(e){
      hideDialog();
      if(BuildConfig.isDebug){
        print(e);
      }
    }
  }

  @override
  void onCreated() {
    super.onCreated();
    // requestCamera();
    PermissionCenterConfig.initPermissionConfig();
    checkLogin();
    // getToken();
  }
}
